package rsj.service.usage.org;

import com.rlyy.aibase.utils.base.Node;
import com.rlyy.aibase.utils.base.TableNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import rsj.api.org.entity.UsageReportParam;
import rsj.sql.org.UsageTestReportForOrgDao;
import rsj.service.export.org.IOrgExportCurrentTable;
import rsj.service.usage.IUsageTemplateMethod;

import java.util.Objects;

/**
 * 机构客户使用情况
 *
 * @author yuanqinglong
 * @since 2021/3/3 16:52
 */
@Component
public class UsageTestReportForOrg implements IOrgCalculateUsage, IUsageTemplateMethod {


    @Autowired
    private UsageTestReportForOrgDao usageTestReportForOrgDao;


    @Override
    public Node countStatistic(UsageReportParam usageReportParam) {
        return usageTestReportForOrgDao.countStatistic(usageReportParam);
    }

    @Override
    public TableNode queryTableByPage(UsageReportParam usageReportParam) {
        return usageTestReportForOrgDao.queryTableByPage(usageReportParam);
    }

    /**
     * 生成查询sql
     *
     * @param usageReportParam 参数
     * @return sql
     */
    @Override
    public String generateQueryStatement(UsageReportParam usageReportParam) {
        String sql = IOrgExportCurrentTable.exportCurrentTableQueryStatement(usageReportParam);
        sql += " LIMIT #{pageSize} OFFSET #{pageNow}" ;
        return sql;
    }


    /**
     * 生成统计总数sql
     *
     * @param usageReportParam 参数
     * @return sql
     */
    @Override
    public String generateCountStatement(UsageReportParam usageReportParam) {
        String countSql = "SELECT COUNT(*) FROM ( SELECT stat_prod_uid " +
                "FROM sys.sys_stat LEFT JOIN sys.sys_orgp orgp ON orgp.orgp_id = stat_orgp_id " +
                "WHERE stat_env = #{environment} AND stat_org_id = #{statOrgId}";
        if (Objects.nonNull(usageReportParam.getStatDate())) {
            countSql += " AND stat_date < #{statDate}";
        }
        countSql += " GROUP BY stat_prod_uid,stat_org_id,stat_prod_name) a ";
        return countSql;
    }


}
